package com.hd.vote.User.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hd.vote.User.entity.Candidate;
import com.hd.vote.User.entity.Vote;
import com.hd.vote.User.mapper.VoteMapper;
import com.hd.vote.User.service.ICandidateService;
import com.hd.vote.User.service.IVoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hd
 * @since 2023-04-14
 */
@Service
public class VoteServiceImpl extends ServiceImpl<VoteMapper, Vote> implements IVoteService {
    @Autowired
    VoteMapper voteMapper;
    @Autowired
    ICandidateService candidateService;
    @Autowired
    IVoteService voteService;
    @Override
    public List<Object> find(String phone) {
        return voteMapper.find(phone);
    }
    @Override
    public HashMap<String ,Object> vote(String phone,String name){
        //返回的map
        HashMap<String, Object> map = new HashMap<>();
        //存储的暂时map的list
        List<Object> list1 = new ArrayList<>();
        QueryWrapper<Vote> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        //根据电话获取投票id
        List<Vote> list = voteService.list(wrapper);
        if (list!=null){
            map.put("msg","OK");
            map.put("code", 1);
            //根据id获取候选人信息
            for (int i = 0; i < list.size(); i++) {
                Candidate byId = candidateService.getById(list.get(i).getCandidateId());
                System.out.println(byId);
                if (byId.getName().equals(name)){
                    byId.setVoteNum(byId.getVoteNum()+1);
                    list.get(i).setVoteNum(list.get(i).getVoteNum()+1);
                    candidateService.updateById(byId);
                    voteService.updateById(list.get(i));
                    HashMap<String,Object> map2=new HashMap<>();
                    map2.put("candidateId",byId.getId());
                    map2.put("candidateName",name);
                    map2.put("voteNum",byId.getVoteNum());
                    System.out.println(map2);
                    list1.add(map2);
                }else {
                    continue;
                }

            }
            System.out.println(list1);
            map.put("date",list1);

        }else {
            map.put("msg","接口操作失败，请联系运维人员");
            map.put("code", -1);
        }
        return map;
    }
}
